package com.mgg.user.service.user.impl;

import java.math.BigDecimal;
import java.util.*;

import com.mgg.common.dao.DaoSupport;
import com.mgg.common.enums.UserRoleEnum;
import com.mgg.common.entity.UserDO;
import com.mgg.user.service.BaseUserService;
import com.mgg.user.service.user.UserSalaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;

@Service("userSalaryService")
public class UserSalaryServiceImpl implements UserSalaryService{

	@Autowired
	private DaoSupport dao;

	@Autowired
    private BaseUserService baseUserService;

	/**
	 * 工资总计，培训工资，拓展工资，育成工资
	 */
	@Override
	public Map<String, Object> countSalaryByMonth(String userId, String monthStr) {
		Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("userId", userId);
        queryMap.put("month", monthStr);
        queryMap.put("type", 1);
		BigDecimal trainSalary = dao.findForObject("UserSalaryMapper.countSalaryByMonth", queryMap);
        queryMap.put("type", 2);
		BigDecimal expandSalary = dao.findForObject("UserSalaryMapper.countSalaryByMonth", queryMap);
        queryMap.put("type", 3);
		BigDecimal growSalary = dao.findForObject("UserSalaryMapper.countSalaryByMonth", queryMap);
		
		BigDecimal salarySum = expandSalary.add(trainSalary).add(growSalary);
        Map<String, Object> result = new HashMap<>();
		result.put("salarySum", salarySum);
		result.put("expandSalary", expandSalary);
		result.put("trainSalary", trainSalary);
		result.put("growSalary", growSalary);
		return result;
	}

	@Override
	public List<Map<String, Object>> listSalaryDetailsByMonth(String userId, String month, String type, Pageable page) {
		PageHelper.startPage(page.getPageNumber(), page.getPageSize());
		Map<String,Object> map = new HashMap<>();
		map.put("userId", userId);
		map.put("type", type);
		if (!month.contains("-")) {
			month = month.substring(0, 4) + "-" + month.substring(4);
		}
		map.put("month", month);
        List<Map<String, Object>> salaryList = new ArrayList<>();
		if ("1".equals(type)) {
            salaryList = dao.findForList("UserSalaryMapper.listTrainSalaryDetailsByMonth", map);
		}
		if ("2".equals(type)) {
            salaryList = dao.findForList("UserSalaryMapper.listExpandSalaryDetailsByMonth", map);
		}
		if ("3".equals(type)) {
            salaryList = dao.findForList("UserSalaryMapper.listGrowSalaryDetailsByMonth", map);
		}
		return salaryList;
	}

	@Override
	public void payExpandingSalary(String userId, Integer orderType, String registTime) {
		boolean isFindManager = false;
		String codes = baseUserService.getUserCodesByUserId(userId);
		BigDecimal sales = new BigDecimal(0);
		List<String> shopCodeList = Arrays.asList(codes.split("-"));
		Collections.reverse(shopCodeList);
		
		for (String shopCode : shopCodeList) {
			UserDO user = baseUserService.getUserByShopCode(shopCode);
			//找总监
			if (isDirector(user)) {
				BigDecimal directorSalary = getUserRebateSalary(orderType,4);
				if (directorSalary.compareTo(new BigDecimal(0)) > 0) {					
					saveExpandingSalary(user.getUserId(),directorSalary, "1", userId, registTime, sales, "");
				}
				break;
			}
			
			//找经理
			if (!isFindManager && isManager(user)) {
				BigDecimal managerSalary = getUserRebateSalary(orderType,3);
				if (managerSalary.compareTo(new BigDecimal(0)) > 0) {							
					saveExpandingSalary(user.getUserId(),managerSalary, "1", userId, registTime, sales, "");
				}
				isFindManager = true;
			}
		}
	}

    /**
     * 获取用户拓展工资奖励金额
     * @param orderType
     * @param userType
     * @return
     */
	private BigDecimal getUserRebateSalary(Integer orderType, Integer userType) {
		Map<String,Object> queryMap = new HashMap<>();
		queryMap.put("orderType", orderType);
		queryMap.put("userType", userType);
		BigDecimal salary = dao.findForObject("UserMapper.getUserRebateSalary", queryMap);
		return salary;
	}

	/**
	 * 插入拓展工资记录
	 * @param userId
	 * @param amount
	 * @param status
	 * @param sourceId
	 * @param starttime
	 * @param remark
	 * @throws Exception
	 */
	void saveExpandingSalary(String userId, BigDecimal amount, String status, String sourceId, 
			String starttime, BigDecimal sales, String remark) {
		Map<String,Object> map = new HashMap<>();
		map.put("user_id", userId);
		map.put("amount", amount);
		map.put("type", "2");
		map.put("status", status);
		map.put("source_user", sourceId);
		map.put("starttime", starttime);
		map.put("remark", remark);
		map.put("sales", sales);
		dao.save("UserSalaryMapper.insertUserSalary", map);
	}
	
	boolean isDirector(UserDO user) {
		return UserRoleEnum.DIRECTOR.getCode().equals(user.getRoleCode());
	}
	
	boolean isManager(UserDO user) {
		return UserRoleEnum.MANAGER.getCode().equals(user.getRoleCode());
	}

}
